﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


using GuessTicketClass.Entity;

using System.Text.RegularExpressions;
using GuessTicketClass.Config;

using GuessTicketClass.Utils;
using System.Threading;
using System.Data.SqlClient;
using System.Net;
using System.IO;
using System.Diagnostics;
using GuessTicketClass.Common;

namespace GuessTicket
{
    public partial class MainForm : Form
    {

        /// <summary>
        /// 启动采集线程
        /// </summary>
        Thread StartCollectionThread;

        public MainForm()
        {
            InitializeComponent();

            Label_CollectProgress.Text = "";

            bt_Pause_And_Goon.Enabled = false;
            bt_Stop.Enabled = false;
        }

        /// <summary>
        /// 开始采集
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_Start_Click(object sender, EventArgs e)
        {
            //TicketRule tr = new TicketRule();
            //tr.RuleList.Add(1);
            //tr.RuleList.Add(2);
            //tr.RuleList.Add(3);
            //tr.RuleList.Add(4);
            //tr.RuleList.Add(5);
            //tr.RuleList.Add(6);
            //tr.RuleList.Add(7);
            //tr.RuleList.Add(8);
            //tr.RuleList.Add(9);
            //tr.RuleList.Add(10);
            //tr.RuleList.Add(11);
            //tr.RuleList.Add(12);
            //tr.RuleList.Add(13);
            //tr.RuleList.Add(14);
            //tr.RuleList.Add(15);
            //tr.RuleList.Add(16);
            //tr.RuleList.Add(17);
            //tr.RuleList.Add(18);
            //tr.RuleList.Add(19);
            //tr.RuleList.Add(20);
            //tr.RuleList.Add(21);
            //tr.RuleList.Add(22);
            //tr.RuleList.Add(23);
            //tr.RuleList.Add(24);
            //tr.RuleList.Add(25);
            //tr.RuleList.Add(26);
            //tr.RuleList.Add(27);
            //tr.RuleList.Add(28);
            //tr.RuleList.Add(29);
            //tr.RuleList.Add(30);
            //tr.RuleList.Add(31);
            //tr.RuleList.Add(32);
            //tr.RuleList.Add(33);


            //ConfigAccess<TicketRule>.SaveConfig(tr);

            //TicketInfo ti = new TicketInfo();
            //TicketInfoList til = new TicketInfoList();
            //ti.PeriodNumber =2333;
            //ti.TicketNumber = "12,34,5,6,3,2";

            //til.TicketList.Add(ti);

            //ti = new TicketInfo();
            //ti.PeriodNumber = 1111;
            //ti.TicketNumber = "12,34,5,6,3,2";

            //til.TicketList.Add(ti);

            //ConfigAccess<TicketInfoList>.SaveConfig(til);



            //// 彩票规则 1-33
            //TicketRule tr = ConfigAccess<TicketRule>.GetConfig();
            //foreach (int item in tr.RuleList)
            //{
            //    if (ruleList.ContainsKey(item))
            //    {
            //        continue;
            //    }
            //    ruleList.Add(item, 0);
            //}



            // 初始化线程
            StartCollectionThread = new Thread(new ThreadStart(RunCollect));

            // 线程 启动
            StartCollectionThread.Start();

            bt_Start.Enabled = false;
            bt_Pause_And_Goon.Enabled = true;
            bt_Stop.Enabled = true;


        }

        /// <summary>
        /// 暂停 或者 继续
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_Pause_And_Goon_Click(object sender, EventArgs e)
        {
            if (bt_Pause_And_Goon.Text == "暂停")
            {
                bt_Pause_And_Goon.Text = "继续";
                bt_Start.Enabled = false;
                bt_Stop.Enabled = true;

                if (StartCollectionThread == null && StartCollectionThread.ThreadState == System.Threading.ThreadState.Running)
                {
                    // 线程 暂停
                    StartCollectionThread.Suspend();
                }

            }
            else
            {
                bt_Pause_And_Goon.Text = "暂停";
                bt_Start.Enabled = false;
                bt_Stop.Enabled = true;
                if (StartCollectionThread == null && StartCollectionThread.ThreadState == System.Threading.ThreadState.Suspended)
                {
                    // ThreadState.Suspended
                    //  线程 继续
                    StartCollectionThread.Resume();
                }
            }
        }

        /// <summary>
        /// 停止
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_Stop_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("停止操作会丢失当前的数据，确认要停止？", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                bt_Start.Enabled = true;
                bt_Pause_And_Goon.Enabled = false;
                bt_Stop.Enabled = false;

                try
                {
                    if (StartCollectionThread == null)
                    {
                        if (StartCollectionThread.ThreadState == System.Threading.ThreadState.Suspended)
                        {
                            // Btn_Start_method 线程 先恢复再停止
                            StartCollectionThread.Resume();
                        }

                        // Btn_Start_method 线程 停止
                        StartCollectionThread.Abort();
                    }

                }
                catch (Exception ex)
                {

                    //写错误日志
                    FileUtil.WriteLogError("操作：线程停止异常，异常：" + ex.Message);
                }



            }

        }


        /// <summary>
        /// 执行采集
        /// </summary>
        private void RunCollect()
        {
            // 历史彩票
            TicketHistory historyList = new TicketHistory();
            TicketInfoList ticketHistoryList = historyList.GetTicketHistoryList();


            // 前几期号码
            int firstTicketNum = 5;
            // 最后一期号码
            int lastTicketNum = 0;
            //// 要计算的号码期数
            //int ticketNums = firstTicketNum + lastTicketNum;

            // 计划的号码组叠加
            for (int i = firstTicketNum + lastTicketNum; i < ticketHistoryList.TicketList.Count; i++)
            {
                TicketInfoList recordList = new TicketInfoList();

                int recordNum = 0;
                // 推算 要计算期数
                while (firstTicketNum + lastTicketNum + recordNum < ticketHistoryList.TicketList.Count)
                {
                    for (int j = 0; j < firstTicketNum + lastTicketNum; j++)
                    {
                        // 添加算概率用的彩票集合
                        recordList.TicketList.Add(ticketHistoryList.TicketList[j + recordNum]);
                    }
                    // 算概率
                    CheckTicketProbability(firstTicketNum, lastTicketNum, recordList, ticketHistoryList.TicketList[firstTicketNum + lastTicketNum + recordNum]);
                    recordNum++;
                    recordList.TicketList.Clear();

                }

                firstTicketNum++;
            }

            // 


            //for (int i = 0; i < til.TicketList.Count; i++)
            //{
            //    //  til.TicketList[i]

            //    if (ticketNums < tempForTicketNum)
            //    {
            //        // 算概率
            //        // 信息显示
            //        DisplayCollectionInfo(string.Format(" i={0}，算{1}组，概率为{2} "
            //            ,i
            //            ,ticketNums
            //            , CheckTicketProbability(firstTicketNum, lastTicketNum, recordList, )
            //            ));

            //        tempForTicketNum = 0;
            //        recordList.Clear();
            //    }
            //    // 添加号码
            //    recordList.Add(til.TicketList[i].TicketNumber);
            //    tempForTicketNum++;

            //}







            //CollectUrlList cul = ConfigAccess<CollectUrlList>.GetConfig();
            //// 为空退出
            //if (cul == null)
            //{
            //    MessageBox.Show("CollectUrlList 对象为空");
            //    return;
            //}

            //CollectionRule cr = ConfigAccess<CollectionRule>.GetConfig();
            //// 为空退出
            //if (cr == null)
            //{
            //    MessageBox.Show("CollectionRule 对象为空");
            //    return;
            //}


            //Stopwatch sw = new Stopwatch();
            //sw.Start();

            ////sw.Stop();
            //TimeSpan TotalTime = sw.Elapsed;//sw.Elapsed记录了刚刚运行的代码段总时间
            ////显示进度
            //DisplayCollectProgress(string.Format("共 {0} 条URL需要采集，目前正在采集第 {1} 个，程序已运行 {2}天 {3} ", cul.Url.Count, i, TotalTime.Days, TotalTime.ToString()));



            //// 采集信息显示
            //DisplayCollectionInfo(string.Format("无法匹配，Url为：{0}", urlStr));
            ////写错误日志
            //FileUtil.WriteLogError("操作：【RunCollect下的foreach (string urlStr in cul.Url) 代码出错】，异常：" + ex.Message);





            MessageBox.Show("完成。");

            // 线程停止
            StartCollectionThread.Abort();
        }

        /// <summary>
        /// 获取组号的历史中奖参数，输入：组号，共预测几组号码，输出：历史中奖的参数
        /// </summary>
        /// <param name="groupNum">组号，共预测几组号码</param>
        /// <returns>历史中奖的参数</returns>
        private List<TicketGroupsInfo> GetTicketListOnGroupNum(int groupNum)
        {
//获取组号的历史中奖参数，然后要怎么处理数据呢？
//第一种：
//1、先把数据按 深度为0的数据分组，如[空]、[3]、[1,3]、[1,1,1]、[1,2,3]等，分组
//
//
//
//
//
//
//
//
//
//
//



            // 为0退出
            if (groupNum == 0)
            {
                return null;
            }
            string selectSql = "select frequency,depth,objticket,DepthZeroInFreq,DepthNoZeroInFreq from TicketGroups where checkgroups=" + groupNum;

            List<TicketGroupsInfo> TicketGroupsList = new List<TicketGroupsInfo>();

            using (DataSet ds = SqlHelper.ExecuteDataSet(selectSql))
            {
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    TicketGroupsInfo model = new TicketGroupsInfo();
                    model.Frequency = item["frequency"].ToString();
                    model.Depth = item["Depth"].ToString();
                    model.ObjTicket = item["ObjTicket"].ToString();
                    model.DepthZeroInFreq = item["DepthZeroInFreq"].ToString();
                    model.DepthNoZeroInFreq = item["DepthNoZeroInFreq"].ToString();

                    TicketGroupsList.Add(model);
                }

            }

            return TicketGroupsList;
        }





        /// <summary>
        ///  彩票概率算法
        /// </summary>
        /// <param name="firstNum"></param>
        /// <param name="lastNum"></param>
        /// <param name="recordList">历史号码</param>
        /// <param name="objTicket">中奖号码</param>
        private void CheckTicketProbability(int firstNum, int lastNum, TicketInfoList recordList, TicketInfo objTicket)
        {

            // 彩票规则 1-33
            TicketParaList tpl = new TicketParaList();
            Dictionary<int, TicketParaInfo> ruleList = tpl.GetTicketParaList();


            // 必须相等
            if (recordList.TicketList.Count != firstNum + lastNum)
            {
                // 信息显示
                DisplayCollectionInfo("recordList.TicketList 与 firstNum+lastNum 必须相等");
                return;
            }

            // firstNum + lastNum 先不计算最后一个号码的对比
            for (int i = 0; i < firstNum + lastNum; i++)
            {
                //深度+1
                foreach (int item in ruleList.Keys)
                {
                    ruleList[item].Depth++;
                }

                string ticketNumber = recordList.TicketList[i].TicketNumber;
                string[] nums = ticketNumber.Split(',');
                foreach (string item in nums)
                {
                    int _ticket = IntUtil.ToSafeInt(item);
                    // 频率+1
                    ruleList[_ticket].Frequency++;
                    // 深度清0
                    ruleList[_ticket].Depth = 0;
                }

            }
            // 频率比较结果
            List<int> frequencyList = new List<int>();
            // 深度比较结果
            List<int> depthList = new List<int>();
            // 深度为0的频度次数
            List<int> depthZeroInFreqList = new List<int>();
            // 深度不为0的频度次数
            List<int> depthNoZeroInFreqList = new List<int>();

            // 比较中奖号码
            string[] objnums = objTicket.TicketNumber.Split(',');
            foreach (string item in objnums)
            {
                int _ticket = IntUtil.ToSafeInt(item);
                // 频率
                frequencyList.Add(ruleList[_ticket].Frequency);
                // 深度
                depthList.Add(ruleList[_ticket].Depth);

                if (ruleList[_ticket].Depth == 0)
                {
                    // 深度为0
                    depthZeroInFreqList.Add(ruleList[_ticket].Frequency);
                }
                else
                {
                    // 深度不为0
                    depthNoZeroInFreqList.Add(ruleList[_ticket].Frequency);
                }
            }

            #region 频率和深度计算

            frequencyList.Sort();
            depthList.Sort();
            depthZeroInFreqList.Sort();
            depthNoZeroInFreqList.Sort();
            // 频率比较结果字符串
            string frequency = string.Empty;
            // 深度比较结果字符串
            string depth = string.Empty;
            // 深度为0在频率中次数比较结果字符串
            string depthZeroInFreq = string.Empty;
            // 深度不为0在频率中次数比较结果字符串
            string depthNoZeroInFreq = string.Empty;

            foreach (int item in frequencyList)
            {
                frequency += item + ",";
            }
            foreach (int item in depthList)
            {
                depth += item + ",";
            }
            foreach (int item in depthZeroInFreqList)
            {
                depthZeroInFreq += item + ",";
            }
            foreach (int item in depthNoZeroInFreqList)
            {
                depthNoZeroInFreq += item + ",";
            }
            frequency = frequency.TrimEnd(',');
            depth = depth.TrimEnd(',');
            depthZeroInFreq = depthZeroInFreq.TrimEnd(',');
            depthNoZeroInFreq = depthNoZeroInFreq.TrimEnd(',');
            #endregion

            // 信息显示
            DisplayCollectionInfo(string.Format(" 算{0}组，频率为{1}，深度为{2}，目标号码为{3} "
                , firstNum + lastNum
                , frequency
                , depth
                , objTicket.TicketNumber));

            SqlParameter[] paraList = new SqlParameter[6];

            paraList[0] = new SqlParameter("@CheckGroups", SqlDbType.Int);
            paraList[0].Value = firstNum + lastNum;

            paraList[1] = new SqlParameter("@Frequency  ", SqlDbType.VarChar, 50);
            paraList[1].Value = frequency;

            paraList[2] = new SqlParameter("@Depth", SqlDbType.VarChar, 50);
            paraList[2].Value = depth;

            paraList[3] = new SqlParameter("@objTicket", SqlDbType.VarChar, 50);
            paraList[3].Value = objTicket.TicketNumber;

            paraList[4] = new SqlParameter("@DepthZeroInFreq", SqlDbType.VarChar, 50);
            paraList[4].Value = depthZeroInFreq;

            paraList[5] = new SqlParameter("@DepthNoZeroInFreq", SqlDbType.VarChar, 50);
            paraList[5].Value = depthNoZeroInFreq;

            string insertSql = @"
insert into TicketGroups(CheckGroups,Frequency,Depth,objTicket,DepthZeroInFreq,DepthNoZeroInFreq) 
values(@CheckGroups,@Frequency,@Depth,@objTicket,@DepthZeroInFreq,@DepthNoZeroInFreq)";

            SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, insertSql, paraList);


        }




        ///// <summary>
        ///// 插入数据库
        ///// </summary>
        ///// <param name="sqlDic"></param>
        //private void InsertSql(Dictionary<string, string> sqlDic)
        //{
        //    try
        //    {
        //        if (sqlDic == null || sqlDic.Count == 0)
        //        {
        //            return;
        //        }
        //        StringBuilder sb = new StringBuilder(200);

        //        sb.Append("insert into ");
        //        sb.Append(ConfigAccess<AppConfig>.GetConfig().TableName);
        //        sb.Append(" ( ");

        //        foreach (string item in sqlDic.Keys)
        //        {
        //            sb.Append(string.Format(" {0},", item));
        //        }
        //        // 移除最后一个逗号 “,” 
        //        sb.Remove(sb.Length - 1, 1);

        //        sb.Append(" ) values( ");

        //        SqlParameter[] paraList = new SqlParameter[sqlDic.Count];

        //        int i = 0;
        //        foreach (string item in sqlDic.Keys)
        //        {
        //            sb.Append(string.Format(" @{0},", item));
        //            paraList[i] = new SqlParameter("@" + item, SqlDbType.VarChar, 2048);
        //            paraList[i].Value = sqlDic[item];
        //            i++;
        //        }

        //        // 移除最后一个逗号 “,” 
        //        sb.Remove(sb.Length - 1, 1);
        //        sb.Append(" )  ");

        //        //// 采集信息显示
        //        //DisplayCollectionInfo("执行插入语句：" + sb.ToString());

        //        SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, sb.ToString(), paraList);

        //    }
        //    catch (Exception ex)
        //    {
        //        //写错误日志
        //        FileUtil.WriteLogError("操作：插入数据库【InsertSql(Dictionary<string, string> sqlDic)】，异常：" + ex.Message);

        //    }
        //}




        /// <summary>
        /// 显示进度信息
        /// </summary>
        /// <param name="msg"></param>
        public void DisplayCollectProgress(string msg)
        {
            try
            {
                Label_CollectProgress.Invoke(
                             new EventHandler(SetCollectProgress),
                             new object[] { msg, EventArgs.Empty }
                         );
            }
            catch
            {


            }

        }

        /// <summary>
        /// UI线程写数据
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="e"></param>
        public void SetCollectProgress(object Sender, EventArgs e)
        {
            if (Sender == null || String.IsNullOrEmpty(Sender.ToString()))
                Label_CollectProgress.Text = "";
            //else if (Sender.ToString() == "0")
            //    SetButtonStatus(ButtonStatus.Empty);
            else
                Label_CollectProgress.Text = (string)Sender;

        }


        /// <summary>
        /// 显示采集信息
        /// </summary>
        /// <param name="msg"></param>
        public void DisplayCollectionInfo(string msg)
        {
            // 采集信息显示
            string msgStr = string.Format("{0}：{1}", DateTime.Now.ToLongTimeString(), msg);

            try
            {
                TB_Collection_Info.Invoke(
                           new EventHandler(TBCollectionInfo_AppendText),
                           new object[] { msgStr, EventArgs.Empty }
                       );
            }
            catch
            {


            }

        }

        /// <summary>
        /// UI线程写数据
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="e"></param>
        public void TBCollectionInfo_AppendText(object Sender, EventArgs e)
        {
            if (Sender == null || String.IsNullOrEmpty(Sender.ToString()))
                TB_Collection_Info.Text = "";
            //else if (Sender.ToString() == "0")
            //    SetButtonStatus(ButtonStatus.Empty);
            else
                TB_Collection_Info.AppendText((string)Sender + Environment.NewLine);

            //写日志
            FileUtil.WriteCollectLog((string)Sender);
        }

        ///// <summary>
        ///// 获取下载保存路径
        ///// </summary>
        ///// <param name="downUrl"></param>
        ///// <returns></returns>
        //private string GetDownPath(string downUrl)
        //{

        //    string parentpath = System.Environment.CurrentDirectory + "\\";

        //    string dateStr = DateTime.Now.ToString("yyyyMMddHH");

        //    //创建配置文件中的下载目录
        //    FileDirectoryUtil.CreateDirectory(parentpath, ConfigAccess<AppConfig>.GetConfig().DownloadPath);

        //    //创建配置文件中的下载目录
        //    FileDirectoryUtil.CreateDirectory(parentpath + "\\" + ConfigAccess<AppConfig>.GetConfig().DownloadPath, dateStr);

        //    string ext = FileUtil.getExtendName(downUrl);
        //    //后缀为空
        //    if (string.IsNullOrEmpty(ext))
        //    {
        //        ext = ".jpg";
        //    }

        //    string filename = DateTime.Now.TimeOfDay.Ticks.ToString();

        //    return parentpath + ConfigAccess<AppConfig>.GetConfig().DownloadPath + "\\" + dateStr + "\\" + filename + ext;

        //}



        private void btn_md5_Click(object sender, EventArgs e)
        {
            string pwd = textBox_pwd.Text;
            if (string.IsNullOrEmpty(pwd))
            {
                MessageBox.Show("请填写md5字符串");
                return;
            }
            MD5Encrypt md5 = new MD5Encrypt();
            DisplayCollectionInfo(md5.GetMD5FromString(pwd, "utf-8"));
        }








    }
}
